#include "apps.h"
#include <string.h>
#include "ff.h"
#include "mdebug.h"
#include "mlog.h"
#include "umm_malloc.h"

#undef MLOG_LEVEL_CUR
#define MLOG_LEVEL_CUR MLOG_LEVEL_ALL

/**
 * 文件系统信息
 */
static FATFS sd_card;

void sd_card_format(void)
{
	FRESULT ret;

	/* 第一个NULL表示MKFS_PARM采用缺省值
	   第二个NULL表示格式化所需的存储空间由堆提供
	   512表示申请的操作缓存为512，此处必须大于一个擦除单元的大小 */
	ret = f_mkfs("0:", NULL, NULL, 512);
	if (FR_OK != ret) {
		MLOG_DEBUG(1,
			mDebugPrintf("f_mkfs: %d", ret);
		);
		while (1);
	}
}

void sd_card_mount(void)
{
	FRESULT ret;

	/* sdFatfs磁盘信息结构体，其地址会被保存到FatFs[]变量中
	   1表示立即挂载，0表示等第一次进行文件操作时在进行挂载 */
	ret = f_mount(&sd_card, "0:", 1);
	if (FR_OK != ret) {
		MLOG_DEBUG(1,
			mDebugPrintf("f_mount: %d", ret);
		);
		while (1);
	}
}

void sd_card_test(void)
{
	FRESULT ret;
	FIL *fp;
	UINT len;
	char str[] = "你好，世界！！！\r\n";

	fp = umm_malloc(sizeof(FIL));
	if (fp == NULL) {
		mDebugPuts("umm_malloc: no enough memory");
		while (1);
	}
	ret = f_open(fp, "0:/1.txt", FA_OPEN_APPEND | FA_READ | FA_WRITE);
	if (FR_OK != ret) {
		mDebugPrintf("f_open: %d\r\n", ret);
		while (1);
	}
	ret = f_write(fp, str, sizeof(str)-1, &len);
	if ((FR_OK != ret) || ((sizeof(str)-1) != len)) {
		mDebugPrintf("f_write: %d %u\r\n", ret, len);
		while (1);
	}
	ret = f_rewind(fp);
	if (FR_OK != ret) {
		mDebugPrintf("f_rewind: %d\r\n", ret);
		while (1);
	}
	memset(str, 0xAA, sizeof(str)-1);
	ret = f_read(fp, str, sizeof(str)-1, &len);
	if ((FR_OK != ret) || ((sizeof(str)-1) != len)) {
		mDebugPrintf("f_read: %d %u\r\n", ret, len);
		while (1);
	}
	mDebugPutStr(str);
	ret = f_close(fp);
	if (FR_OK != ret) {
		mDebugPrintf("f_close: %d\r\n", ret);
		while (1);
	}
	ret = f_open(fp, "0:/1.txt", FA_OPEN_EXISTING | FA_READ);
	if (FR_OK != ret) {
		mDebugPrintf("f_open: %d\r\n", ret);
		while (1);
	}
	char *p = (char *)umm_malloc(1024);
	ret = f_read(fp, p, 1024, &len);
	if ((FR_OK != ret) || 0 == len) {
		mDebugPrintf("f_read: %d %u\r\n", ret, len);
		while (1);
	}
	p[len] = '\0';
	mDebugPutStr(p);
	ret = f_close(fp);
	if (FR_OK != ret) {
		mDebugPrintf("f_close: %d\r\n", ret);
		while (1);
	}
	umm_free(fp);
	umm_free(p);
}
